package xddq

import (
	"fmt"
	"time"
	D "websocket_apn/define"
	"websocket_apn/log"
	"websocket_apn/proto"
)

// 判断一个时间是否在今日的21:30:00前
func isBeforeNineThirty(t time.Time) bool {
	now := time.Now()
	todayNineThirty := time.Date(now.Year(), now.Month(), now.Day(), 21, 30, 0, 0, now.Location())
	return t.Before(todayNineThirty)
}

// 判断一个时间是否在今日的22:00:00前
func isBeforeTenThirty(t time.Time) bool {
	now := time.Now()
	todayNineThirty := time.Date(now.Year(), now.Month(), now.Day(), 21, 30, 0, 0, now.Location())
	return t.Before(todayNineThirty)
}

// 判断是否需要加入灵阵
func (xd *XdDriver) CheckJuLingZhenInfoData(allInfo []D.JuLingZhenInfo) {
	//joinFlag := false
	currentTime := time.Now()
	for _, info := range allInfo {
		//已经加入灵阵
		if info.IsSelf {
			log.Infof("%+v", info)
			if xd.UserData.UserID != info.ID {
				log.Infof("当前已经加入[%s]的聚灵阵", info.Name)
				task := xd.GetTaskByID(proto.S_GATHER_ENERGY_FIRST_LIST_VIEW)
				task.Enabled = false
				return
			}
		} else if info.Num < 5 {
			//21:30前随机加入空的灵阵
			if currentTime.Hour() < 21 || (currentTime.Hour() == 21 && currentTime.Minute() < 30) {
				if isBeforeNineThirty(info.Time) && isBeforeNineThirty(time.Now()) {
					log.Infof("开始加入[%s]的聚灵阵，%v", info.Name, info)
					xd.Send(proto.Get_Cmd_Data(xd.userInfo.PlayerId, proto.S_GATHER_ENERGY_ATTEND_NEW, fmt.Sprintf("08%s", info.LzID)))
					//joinFlag = true
					break
				}
			} else {
				//22:00前加入超过15个小时的灵阵
				if info.Time.Sub(currentTime) > 15*time.Hour {
					log.Infof("开始加入[%s]的聚灵阵，%v", info.Name, info)
					xd.Send(proto.Get_Cmd_Data(xd.userInfo.PlayerId, proto.S_GATHER_ENERGY_ATTEND_NEW, fmt.Sprintf("08%s", info.LzID)))
					//joinFlag = true
					break
				}
			}
		}
	}
	//
	//if !joinFlag && currentTime.Hour() > 21 || (currentTime.Hour() == 21 && currentTime.Minute() >= 30) {
	//}
}

// 判断是否需要使用灵气升级
func (xd *XdDriver) CheckJuLingZhenLingQiInfoData(info D.JuLingZhenLingQiInfo) {
	if len(info.ID) > 0 && xd.UserData.ChopDownTree.LingQiNum > 100000 {
		log.Infof("聚灵阵-开始灵气转化，%s 当前剩余灵气%d", info.ID, xd.UserData.ChopDownTree.LingQiNum)
		xd.Send(proto.Get_Cmd_Data(xd.userInfo.PlayerId, proto.S_GATHER_ENERGY_TRANSFORM, fmt.Sprintf("08%s", info.ID)))

		num := xd.UserData.ChopDownTree.LingQiNum / 100000
		startId := proto.ParaIntDataByHexStr(info.ID)
		for ; num > 0; num-- {
			log.Infof("聚灵阵-开始灵气转化，%s 当前剩余灵气%d", info.ID, xd.UserData.ChopDownTree.LingQiNum)
			xd.Send(proto.Get_Cmd_Data(xd.userInfo.PlayerId, proto.S_GATHER_ENERGY_TRANSFORM, fmt.Sprintf("08%s", info.ID)))
			startId++
			xd.UserData.ChopDownTree.LingQiNum -= 100000
			info.ID = proto.BytesToHexStr(proto.IntDataToBytes(startId))
			if len(info.ID) == 2 {
				info.ID += "01"
			}
		}
	}
}
